//
//  SGLoginViewController.m
//  HuaMuJinRong
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SGLoginViewController.h"
#import "SGRegisterViewController.h"
#import "SGFindPassWordBackViewController.h"
#import "SGLoginButton.h"
#import "SetGestureLockViewController.h"
#import "TabViewController.h"
#import "GesDatabase.h"
#import "ExperienceViewController.h"
@interface SGLoginViewController ()<HTTPClientDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet SGLoginTextField *userNameTextField;
@property (weak, nonatomic) IBOutlet SGLoginTextField *passWordTextField;
@property (weak, nonatomic) IBOutlet UIButton *passWordSecureButton;
@property (weak, nonatomic) IBOutlet SGLoginButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *forgetButton;

@property (nonatomic, strong) NetWorkClient *requestClient;

@end

@implementation SGLoginViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    if(self.backType == RegisterEnter){
        [self initNavBarTitle:@"登录" andLeftItemName:@"" andRightItemName:@""];
        [self.navigationItem setHidesBackButton:TRUE animated:NO];
        _userNameTextField.text = AppDelegateInstance.firstLoginNameStr;
    }else{
      
      [self initNavBarTitle:@"登录" andLeftItemName:@"返回" andRightItemName:@""];
        _userNameTextField.text = nil;

   
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    
    [self resetNavigationBar];
    if (_requestClient) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
  
    [self initView];
}

- (void)initView {

    _userNameTextField.font = KFontSize(14);
    _passWordTextField.font = KFontSize(14);
    _forgetButton.titleLabel.font = KFontSize(14);
    _nextButton.titleLabel.font = KFontSize(16);
    _registerButton.titleLabel.font = KFontBoldSize(22);
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_userNameTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_passWordTextField];
    _userNameTextField.delegate = self;
    _passWordTextField.delegate = self;
    
    /**
     *  初始化  按钮为  不可点击状态
     */
    _nextButton.isActive = NO;
    _nextButton.clipsToBounds = YES;
    _nextButton.layer.cornerRadius = 4.0f;
    
    [_passWordSecureButton setImage:[UIImage imageNamed:@"passWord_secure_no"] forState:UIControlStateNormal];
    [_passWordSecureButton setImage:[UIImage imageNamed:@"passWord_secure_yes"] forState:UIControlStateSelected];
}

- (void)back {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(backAction)]) {
        [self.delegate backAction];
    
    }
    if (self.backType == SecuritySet) {
        //返回首页
        
        [self dismissViewControllerAnimated:YES completion:nil];
        
        
        TabViewController *tabViewController = [[TabViewController alloc] init];
        AppDelegateInstance.window.rootViewController = tabViewController;
//        [self dismissViewControllerAnimated:YES completion:nil];
//
//        TabViewController *tabViewController = [TabViewController shareTableView];
//        tabViewController.selectedIndex = 0;
//        AppDelegateInstance.window.rootViewController = tabViewController;
        
    }else if (self.backType == ChangeRootView) {
        //返回首页
        [self dismissViewControllerAnimated:YES completion:nil];
        
        TabViewController *tabViewController = [TabViewController shareTableView];
        tabViewController.selectedIndex = 0;
        AppDelegateInstance.window.rootViewController = tabViewController;
        
    }else if (self.backType == EnterBackground) {
        //返回首页
        [self dismissViewControllerAnimated:YES completion:nil];
        
        TabViewController *tabViewController = [TabViewController shareTableView];
        tabViewController.selectedIndex = 0;
        AppDelegateInstance.window.rootViewController = tabViewController;
        
    }else if (self.backType == OtherLoginEnter) {
        //返回首页
        [self dismissViewControllerAnimated:YES completion:nil];
        
        TabViewController *tabViewController = [TabViewController shareTableView];
        tabViewController.selectedIndex = 0;
        AppDelegateInstance.window.rootViewController = tabViewController;
    }else if (self.backType == RegisterEnter){
        
//        AppDelegateInstance.window.rootViewController = nil;
//        TabViewController *tabViewController = [TabViewController shareTableView];
//        tabViewController.selectedIndex = 3;
//        AppDelegateInstance.window.rootViewController = tabViewController;
        ExperienceViewController *experVC = [[ExperienceViewController alloc] init];
        experVC.isFirstLogin = YES;
        [self.navigationController pushViewController:experVC animated:YES];
        
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    //[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Action
- (void)loginSuccess {
    
    // 保存账号密码到UserDefault
    [[AppDefaultUtil sharedInstance] setDefaultUserName:AppDelegateInstance.userInfo.userName];// 保存用户昵称
    [[AppDefaultUtil sharedInstance] setDefaultAccount:_userNameTextField.text];// 保存用户账号
    NSString *pwdStr = [NSString encrypt3DES:_passWordTextField.text key:DESkey];//用户密码3Des加密
    [[AppDefaultUtil sharedInstance] setDefaultUserPassword:pwdStr];// 保存用户密码（des加密）
    [[AppDefaultUtil sharedInstance] setDefaultHeaderImageUrl:AppDelegateInstance.userInfo.userImg];// 保存用户头像
    [[AppDefaultUtil sharedInstance] setdeviceType:AppDelegateInstance.userInfo.deviceType];// 保存设备型号
    
    NSString *account=[[AppDefaultUtil sharedInstance] getDefaultAccount];
    NSString *gestureState=[[GesDatabase getInstance] getGestureState:account];
    DLOG(@"gestureState-->%@-->%@",account,gestureState);
    //判断最后一次登录的账户是否设置手势密码,有则需要开启
    if([gestureState isEqualToString:@"1"]) {
        [self back];
    }else {
       
        [self back];
        return;
        
        //设置手势密码
        SetGestureLockViewController *setGesturesVC = [[SetGestureLockViewController alloc]init];
        setGesturesVC.backType = 1;
        setGesturesVC.superController = self;
        if (AppDelegateInstance.isFirstLogin && [AppDelegateInstance.firstLoginNameStr isEqualToString:_userNameTextField.text]) {
            setGesturesVC.isGoExperience = YES;
        }
        [self presentViewController:setGesturesVC animated:NO completion:^{
            for (UIView *subView in self.view.subviews) {
                [subView removeFromSuperview];
            }
        }];
    }
    
}

//密码  显示
- (IBAction)passWordSecureButtonClick:(id)sender {
    UIButton *btn=(UIButton *)sender;
    _passWordTextField.secureTextEntry=!_passWordTextField.isSecureTextEntry;
    btn.selected=!btn.selected;
}

- (IBAction)nextButtonClick:(id)sender {
    
    if (_userNameTextField.text == nil || _userNameTextField.text.length==0) {
        [SVProgressHUD showErrorWithStatus:@"请输入用户名！"];
        return;
    }
    if (_passWordTextField.text == nil || _passWordTextField.text.length==0) {
        [SVProgressHUD showErrorWithStatus:@"请输入登录密码！"];
        return;
    }
   
    [SVProgressHUD showWithStatus:@"登录中..."];
    
    [self loginRequestData];
}

//忘记密码
- (IBAction)forgotPassWordButtonClick:(id)sender {
    SGFindPassWordBackViewController *findPassWordBackVC=[[SGFindPassWordBackViewController alloc] initWithNibName:@"SGFindPassWordBackViewController" bundle:nil];
    [self.navigationController pushViewController:findPassWordBackVC animated:YES];
}

//注册
- (IBAction)registerButtonClick:(id)sender {
    SGRegisterViewController *registerVc = [[SGRegisterViewController alloc] initWithNibName:@"SGRegisterViewController" bundle:nil];
    [self.navigationController pushViewController:registerVc animated:YES];
}

- (void)textFieldValueChanged {
    if (![_userNameTextField.text isEqualToString:@""]&&![_passWordTextField.text isEqualToString:@""]) {
        _nextButton.isActive=YES;
    }else{
        _nextButton.isActive=NO;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _userNameTextField) {
        [_passWordTextField becomeFirstResponder];
    }else if (textField == _passWordTextField) {
        [_passWordTextField resignFirstResponder];
        [self nextButtonClick:_nextButton];
    }
    
    return YES;
}

#pragma mark - Data
- (void)loginRequestData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    NSString *name = _userNameTextField.text;
    NSString *password = [NSString encrypt3DES:_passWordTextField.text key:DESkey];
    [parameters setObject:@"1" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:name forKey:@"name"];
    [parameters setObject:password forKey:@"pwd"];
    if(AppDelegateInstance.userId != nil && AppDelegateInstance.channelId != nil)
    {
        [parameters setObject:AppDelegateInstance.userId forKey:@"userId"];
        [parameters setObject:AppDelegateInstance.channelId forKey:@"channelId"];
        
    }else{
        [parameters setObject:@"" forKey:@"userId"];
        [parameters setObject:@"" forKey:@"channelId"];
    }
    [parameters setObject:@"2" forKey:@"deviceType"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

//HTTPClientDelegate
- (void)startRequest {
    
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj
{
    NSDictionary *dics=(NSDictionary *)obj;
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        [SVProgressHUD dismiss];
        //处理登录数据
        [CommonClass loginSuccessWithDictionary:dics];
        
       
        [self loginSuccess];
        
//        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error
{
    [SVProgressHUD dismiss];
    [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"];
}

-(void) networkError
{
    [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
